import StatusBar from '@/components/status-bar/StatusBar';
import React, { useCallback, useMemo, useState, useRef } from 'react';
import { GroupPageModel } from '@/service/group';
import { MonitorPageModel } from '@/types/monitor';
import ToolBar from '@/page-compoennt/miner/main/ToolBar';
import Pagination from '@/components/pagination/Pagination';
import styles from './index.module.less';
import { Miner } from '@/types/miner';
import useForceUpdate from '@/hooks/forceUpdate';
import { AiOutlineClose, AiOutlineCopy, AiOutlineEdit } from 'react-icons/all';
import { Button, Dropdown, Menu } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import MinerItemsElement from '@/page-compoennt/miner/main/MinerItemsElement';
import GroupDropDown from '@/page-compoennt/miner/moveToGroupAndMoreHandle/GroupDropDown';
import MoreHandleDropDown from '@/page-compoennt/miner/moveToGroupAndMoreHandle/MoreHandleDropDown';
import {
  FetchMinerParams,
  useFetchMinerSwr,
} from '@/hooks/swr/useFetchMinerSwr';
import MinerNameEditModal from '@/components/miner-name-edit/MinerNameEditModal';

interface IPageProps {
  groupModel: GroupPageModel | undefined;
  monitorInfo: MonitorPageModel | undefined;
  mid: number;
  // gid 没有分组时候用0
  gid: number;
}

function MinerMain(props: IPageProps) {
  const { mid, gid, groupModel, monitorInfo } = props;

  const [fetchMinerParams, setFetchMinerParams] = useState<FetchMinerParams>({
    status: -1,
    page: 1,
    limit: 10,
    order: '',
    mid: -1,
    gid: 0,
    search: '',
  });
  const [isAutoReFresh, setIsAutoReFresh] = useState(false);
  const [minerNameEditModalVisible, setMinerNameEditModalVisible] =
    useState(false);
  const [curMinerNameEdit, setCurMinerNameEdit] = useState({
    name: '',
    mac: '',
  });
  const [openedCardInfoId, setOpenedCardInfoId] = useState('');

  const {
    data: minerModel,
    error,
    isValidating,
    mutate,
  } = useFetchMinerSwr(
    mid,
    groupModel,
    monitorInfo,
    gid,
    fetchMinerParams,
    isAutoReFresh,
  );

  const mutateMiner = useCallback(() => {
    mutate().then();
  }, [mutate]);

  const toggle = (flag = true) => {
    if (flag) {
      checkedMinerMap.current = new Map(
        minerModel?.minerList.map((miner) => {
          return [miner.mac, miner];
        }),
      );
      forceUpdate();
    } else {
      checkedMinerMap.current.clear();
      forceUpdate();
    }
  };

  const setParams = useCallback(
    (params: Omit<keyof FetchMinerParams, any>) => {
      setFetchMinerParams((minerParams) => {
        return {
          ...minerParams,
          ...params,
        };
      });
      toggle(false);
      setOpenedCardInfoId('');
    },
    [setFetchMinerParams],
  );

  const checkedMinerMap = useRef<Map<string, Miner>>(new Map());
  const forceUpdate = useForceUpdate();

  // 单个勾选的时候
  const checkMinerCard = useCallback(
    (miner: Miner, e: React.MouseEvent<HTMLElement>) => {
      e.stopPropagation();
      const hasMiner = checkedMinerMap.current.get(miner.mac);
      if (hasMiner) {
        checkedMinerMap.current.delete(miner.mac);
      } else {
        checkedMinerMap.current.set(miner.mac, miner);
      }
      forceUpdate();
    },
    [checkedMinerMap.current],
  );

  // 全选按钮
  const toggleAll = () => {
    if (!minerModel) {
      return;
    }
    if (minerModel.minerList.length === 0) {
      return;
    }
    if (checkedMinerMap.current.size < minerModel.minerList.length) {
      toggle(true);
      return;
    }
    toggle(false);
  };

  const handlePageChange = useCallback(
    (page: number, limit: number) => {
      setFetchMinerParams((minerParams) => {
        return {
          ...minerParams,
          page,
          limit,
        };
      });
    },
    [setFetchMinerParams],
  );

  const openNameEditModal = (name: string, mac: string) => {
    setCurMinerNameEdit({
      name,
      mac,
    });
    setMinerNameEditModalVisible(true);
  };

  return (
    <>
      <StatusBar
        currentStatus={fetchMinerParams.status}
        loading={isValidating}
        {...groupModel?.currentGroup?.miner_count}
        miner_num={groupModel?.currentGroup?.miner_num}
        changeCurrentStatus={setParams}
      />
      <ToolBar
        search={fetchMinerParams.search}
        setParams={setParams}
        isAutoReFresh={isAutoReFresh}
        setIsAutoReFresh={setIsAutoReFresh}
        loading={isValidating}
        toggleAll={toggleAll}
      />
      <MinerItemsElement
        checkedMinerMap={checkedMinerMap}
        checkMinerCard={checkMinerCard}
        isValidating={isValidating}
        minerModel={minerModel}
        toggle={toggle}
        openedCardInfoId={openedCardInfoId}
        setOpenedCardInfoId={setOpenedCardInfoId}
        groupModel={groupModel}
        mutateMiner={() => mutateMiner()}
        openNameEditModal={openNameEditModal}
      />

      <Pagination
        current={fetchMinerParams.page}
        pageSize={fetchMinerParams.limit}
        total={minerModel?.total || 0}
        onChange={handlePageChange}
      />
      {checkedMinerMap.current.size ? (
        <div
          id="minerMoreCheckHandleWrap"
          className={`flex jc-center ${styles.minerMoreCheckHandleWrap}`}
        >
          <div className={`flex ai-center ${styles.minerMoreCheckHandleInner}`}>
            <div className={`flex-1 ${styles.count}`}>
              已选 {checkedMinerMap.current.size} 台
            </div>
            <div>
              <GroupDropDown
                mutateMiner={() => mutateMiner()}
                groupModel={groupModel}
                miners={Array.from(checkedMinerMap.current.keys())}
                containerId="minerMoreCheckHandleWrap"
              >
                <Button
                  size="small"
                  style={{
                    backgroundColor: '#425067',
                    color: '#F1FDFF',
                    border: '0',
                    height: '28px',
                    marginRight: '8px',
                  }}
                >
                  移动至
                  <DownOutlined />
                </Button>
              </GroupDropDown>
            </div>
            <div>
              <MoreHandleDropDown
                miners={Array.from(checkedMinerMap.current.keys())}
                mid={mid}
                mutateMiner={mutateMiner}
              >
                <Button
                  size="small"
                  style={{
                    backgroundColor: '#425067',
                    color: '#F1FDFF',
                    border: '0',
                    height: '28px',
                    marginRight: '14px',
                    position: 'relative',
                  }}
                >
                  更多操作
                  <DownOutlined />
                </Button>
              </MoreHandleDropDown>
            </div>
            <AiOutlineClose
              onClick={() => toggle(false)}
              style={{
                color: '#8695A0',
                fontSize: '20px',
                lineHeight: '22px',
                marginRight: '15px',
              }}
            />
          </div>
        </div>
      ) : null}

      <MinerNameEditModal
        mid={mid}
        mac={curMinerNameEdit.mac}
        nameStr={curMinerNameEdit.name}
        visible={minerNameEditModalVisible}
        setVisible={setMinerNameEditModalVisible}
        afterEdit={mutateMiner}
      />
    </>
  );
}

export default MinerMain;
